package com.songshuai.webapi.permission.service.impl;

import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.permission.dao.*;
import com.songshuai.webapi.permission.dto.po.FunctionListQueryPojo;
import com.songshuai.webapi.permission.dto.request.NavigationAddReqDto;
import com.songshuai.webapi.permission.dto.request.NavigationRelateFunctionReqDto;
import com.songshuai.webapi.permission.dto.request.NavigationUpdateReqDto;
import com.songshuai.webapi.permission.dto.response.*;
import com.songshuai.webapi.permission.model.*;
import com.songshuai.webapi.permission.service.CurrentUserService;
import com.songshuai.webapi.permission.service.NavigationsService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NavigationsServiceImpl implements NavigationsService {

    @Autowired
    private YxNavigationsMapper navigationsMapper;

    @Autowired
    private YxNavigationFunctionMapper navigationFunctionMapper;

    @Autowired
    private YxUserNavigationsMapper userNavigationsMapper;

    @Autowired
    private YxUserNavigationFunctionMapper userNavigationFunctionMapper;

    @Autowired
    private YxFunctionsMapper yxFunctionsMapper;

    @Autowired
    private CurrentUserService currentUserService;

    @Override
    public List<NavigationListResDto> queryLoginNavigationList(Integer appId) {
        //查找所有一级菜单
        List<NavigationListResDto> parentList = new ArrayList<>();
        if(currentUserService.CheckIsSysAdmin()){//超级管理员
            parentList = navigationsMapper.queryAdminParentNavigationList(appId);
        } else {//普通用户
            parentList =  navigationsMapper.queryParentNavigationList(currentUserService.getUserId(), appId);
        }
        if(CollectionUtils.isNotEmpty(parentList)){
            //查找所有非一级菜单
            List<NavigationListResDto> allChildList = new ArrayList<>();
            if(currentUserService.CheckIsSysAdmin()){
                allChildList = navigationsMapper.queryAdminAllChildNavigationList(appId);
            } else {
                allChildList = navigationsMapper.queryAllChildNavigationList(currentUserService.getUserId(),appId);
            }
            if(CollectionUtils.isNotEmpty(allChildList)){
                for(NavigationListResDto parent:parentList) {
                    queryChildListByParentId(parent,parent.getId(),allChildList);
                }
            }
        }
        return parentList;
    }

    //根据父id查找当前子菜单
    private void queryChildListByParentId(NavigationListResDto parent,Integer parentId,List<NavigationListResDto> allChildList){
        List<NavigationListResDto> childList = new ArrayList<>();
        for(NavigationListResDto child : allChildList){
            if(parentId.equals(child.getParentId())){
                queryChildListByParentId(child,child.getId(),allChildList);
                childList.add(child);
            }
        }
        parent.setChildList(childList);
    }

    @Override
    public NavigationResDto queryNavigationById(Integer id){
        NavigationResDto resDto = new NavigationResDto();
        YxNavigations entity = navigationsMapper.queryNavigationById(id);
        PropertiesUtil.copyProperties(entity,resDto);
        return resDto;
    }

    @Override
    public NavigationAddOrUpResDto addNavigation(NavigationAddReqDto parmDto) {
        YxNavigations entity = new YxNavigations();
        PropertiesUtil.copyProperties(parmDto,entity);
        entity.setCreateBy(currentUserService.getUserId());
        entity.setCreateTime(new Date());
        if(navigationsMapper.addNavigation(entity) <= 0){
            throw new BusinessException("新增菜单失败", ResultStatus.EXCEPTION);
        }
        NavigationAddOrUpResDto resDto = new NavigationAddOrUpResDto();
        PropertiesUtil.copyProperties(entity,resDto);
        return resDto;
    }

    @Override
    public NavigationAddOrUpResDto updateNavigation(NavigationUpdateReqDto parmDto) {
        YxNavigations entity = new YxNavigations();
        PropertiesUtil.copyProperties(parmDto,entity);
        if(navigationsMapper.updateNavigation(entity) <= 0){
            throw new BusinessException("修改菜单失败", ResultStatus.EXCEPTION);
        }
        NavigationAddOrUpResDto resDto = new NavigationAddOrUpResDto();
        PropertiesUtil.copyProperties(entity,resDto);
        return resDto;
    }

    @Override
    @Transactional
    public boolean deleteNavigation(Integer id) {
        return delete(id);
    }

    private boolean delete(Integer id){
        //根据id获取该菜单所有子菜单
        List<Integer> childIdList = navigationsMapper.queryChildIdList(id);
        if(CollectionUtils.isNotEmpty(childIdList)){
            for(Integer childId : childIdList){
                delete(childId);
            }
        }
        //删除菜单功能关系
        navigationFunctionMapper.deleteNavFuncRelation(id);
        //删除菜单用户关系
        userNavigationsMapper.deleteNavUserRelation(id);
        //删除菜单功能用户关系
        userNavigationFunctionMapper.deleteNavUserFuncRelation(id);
        //删除角色菜单关系
        navigationsMapper.deleteNavRoleRelation(id);
        //删除角色菜单功能关系
        yxFunctionsMapper.deleteNavRoleFuncRelation(id);
        //删除菜单
        return navigationsMapper.deleteNavigationById(id) > 0;
    }

    @Override
    public List<FunctionListQueryResDto> queryFunctionListByNav(Integer navigationId, Integer appId){
        List<FunctionListQueryPojo> pojoList = navigationsMapper.queryFunctionListByNav(navigationId,appId);
        List<FunctionListQueryResDto> resDtoList = pojoList.stream().map(pojo -> {
            FunctionListQueryResDto resDto = new FunctionListQueryResDto();
            PropertiesUtil.copyProperties(pojo,resDto);
            return resDto;
        }).collect(Collectors.toList());
        return resDtoList;
    }


    @Override
    @Transactional
    public boolean relateFunction(NavigationRelateFunctionReqDto reqDto){
        //删除菜单功能关系
        navigationFunctionMapper.deleteNavFuncRelation(reqDto.getNavigationId());
        if(CollectionUtils.isNotEmpty(reqDto.getFunctionIdList())) {//当功能列表不为空时
            //删除菜单功能用户关系，不在这些功能列表之内的
            navigationsMapper.deleteNavUserFuncRelation(reqDto);
            //删除菜单功能角色关系，不在这些功能列表之内的
            navigationsMapper.deleteNavRoleFuncRelation(reqDto);
            //关联菜单功能
            return navigationsMapper.relateFunction(currentUserService.getUserId(),reqDto) > 0;
        } else {//当功能列表为空时
            //删除菜单功能用户关系
            userNavigationFunctionMapper.deleteNavUserFuncRelation(reqDto.getNavigationId());
            //删除菜单功能角色关系
            yxFunctionsMapper.deleteNavRoleFuncRelation(reqDto.getNavigationId());
        }
        return true;
    }

}